<template>
    <section style="position: relative;">
        <section style="text-align: center; padding-top: 30px;">
            <button @click="addData">Socket添加</button>
            <button @click="delData" style="margin-left: 10px;">Socket删除</button>
        </section>
        <div v-show="isLoading" style="padding: 12px 0; width: 100%; position: absolute; top: 0; left: 0; text-align: center; color: #399;">
            <img src="./loading.jpg" alt="">
            <p>数据加载中...</p>
        </div>
        <Carousel :dataSource="list" @moveOk="handleMoveOk" />
    </section>
</template>

<script>
import Carousel from './Carousel';
export default {
    components: {Carousel},
    data () {
        return {
            list: [],
            n: 0
        };
    },

    created () {
        // 第一次获取数据
        this.getHttpData();
    },

    methods: {
        // 子级运动完成
        handleMoveOk () {
            if (this.list.length <= 1) {
                return false;
            }
            this.list.push(this.list.shift());
        },
        // 获取http接口数据
        getHttpData () {
            this.isLoading = true;
            setTimeout(() => {
                this.list = Object.assign([], [
                    this._createdTestData(),
                    this._createdTestData()
                ]);
                this.isLoading = false;
            }, 2000);
        },
        // Socket新增
        addData () {
            this.list.splice(1, 0, this._createdTestData());
        },
        // Socket删除
        delData () {
            // 随机删除数据中的某一项
            let random = this.getRandomIntInclusive(0, this.list.length - 1);
            this.list.splice(random, 1);
        },

        // 创建测试数据
        _createdTestData () {
            this.n++;
            return {id: this.n, text: `test data - ${this.n}`};
        },

        // 创建随机数
        getRandomIntInclusive (min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min; // 含最大值，含最小值
        }
    }
}
</script>

<style lang="scss">

</style>